package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;


/*    @GetMapping("/dish/{id}")
    public R<SetmealDto> showSetmeal(@PathVariable long id){
*/
    /**
     * 移动端-》点击套餐显示对应的菜品信息
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<SetmealDishDto>> showSetMeal(@PathVariable Long id) {
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getSetmealId, id);
        //获取到菜品集合，但是菜品没图片需要到dish表中拿
        List<SetmealDish> setmealDishes = setmealDishService.list(wrapper);
        List<SetmealDishDto> list = setmealDishes.stream().map(item -> {
            SetmealDishDto setmealDishDto = new SetmealDishDto();
            BeanUtils.copyProperties(item, setmealDishDto);
            Long dishId = item.getDishId();
            Dish dish = dishService.getById(dishId);
            String image = dish.getImage();
            setmealDishDto.setImage(image);
            return setmealDishDto;
        }).collect(Collectors.toList());
        return R.success(list);
    }
    /**
     * 根据分类ID查询套餐
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    //第一次查询都去mysql数据库中查询并添加进redis缓存中，下次查询直接访问redis缓存
    @Cacheable(value = "setmealCache",key = "'setmeal_'+#setmeal.categoryId")
    public R<List<Setmeal>> setmealList(Setmeal setmeal) {
        //创建套餐条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        //条件：查询分类id对比
        wrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        //条件：查询状态码比较
        wrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        //调用方法,查询所有套餐
        List<Setmeal> setmealList = setmealService.list(wrapper);
        //返回数据
        return R.success(setmealList);
    }

    /**
     * 套餐起售
     *
     * @param
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    public R<String> updateStatus(@RequestParam List<Long> ids) {
        log.info("请求修改的套餐id:{}", ids);
        //调用套餐service层方法将ids封装成list对象
        List<Setmeal> setmealList = setmealService.listByIds(ids);
        //遍历
        for (Setmeal setmeal : setmealList) {
            //通过套餐对象获取套餐id
            Long setmealId = setmeal.getId();
            //套餐菜品条件构造器
            LambdaQueryWrapper<SetmealDish> setmealDishWrapper = new LambdaQueryWrapper<>();
            //条件：查询套餐id
            setmealDishWrapper.eq(SetmealDish::getSetmealId, setmealId);
            //调用套餐菜品service层list方法，封装成list集合
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishWrapper);
            //遍历
            for (SetmealDish setmealDish : setmealDishList) {
                //通过setmealDish对象获取菜品id
                Long dishId = setmealDish.getDishId();
                //创建菜品的条件构造器
                LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
                //条件：查询菜品id
                dishWrapper.eq(Dish::getId, dishId);
                //条件：查询状态是否为0
                dishWrapper.eq(Dish::getStatus, 0);
                //调用菜品service层count方法，通过条件构造器对象查询数量
                int count = dishService.count(dishWrapper);
                //判断:如果count大于0
                if (count > 0) {
//                    throw new CustomException("当前套餐下的菜品已经停售，无法起售该套餐");
                    return R.error("当前套餐下的菜品已经停售，无法起售该套餐");
                }
            }
        }
        for (Setmeal setmeal : setmealList) {
            setmeal.setStatus(1);
            setmealService.updateById(setmeal);
        }
        return R.success("启售成功！");
    }

    /**
     * 套餐停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> updateStatu(@RequestParam List<Long> ids) {
        List<Setmeal> setmealList = setmealService.listByIds(ids);
        for (Setmeal setmeal : setmealList) {
            setmeal.setStatus(0);
            setmealService.updateById(setmeal);
        }
        return R.success("停售成功");
    }

    /**
     * 回显套餐信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> get(@PathVariable Long id) {
        log.info("请求需要回显的id:{}", id);
        SetmealDto setmealDto = setmealService.getByIdWithSetmeal(id);
        return R.success(setmealDto);
    }


    /**
     * 修改套餐信息
     *
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",key = "'setmeal_'+setmealDto.categoryId")
    public R<String> update(@RequestBody SetmealDto setmealDto) {
        log.info("需要修改的套餐信息：{}", setmealDto.toString());
        setmealService.updateWithDish(setmealDto);
        return R.success("修改套餐成功~");
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids) {
        log.info("ids:{}", ids);
        // 删除套餐的同时,需要将关联的菜品删除
        setmealService.removeWithDish(ids);
        return R.success("套餐数据删除成功");
    }

    /**
     * 分页查询套餐信息
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {

        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);

        setmealService.page(pageInfo, wrapper);
        //=================转存并封装数据
        Page<SetmealDto> setmealDtoPageInfo = new Page<>();
        BeanUtils.copyProperties(pageInfo, setmealDtoPageInfo, "records");

        List<SetmealDto> setmealDtoList = pageInfo.getRecords().stream().map(item -> {
            Category category = categoryService.getById(item.getCategoryId());
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);
            setmealDto.setCategoryName(category.getName());
            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPageInfo.setRecords(setmealDtoList);
        return R.success(setmealDtoPageInfo);
    }

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息：{}", setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }
}    